
#include "teletype.h"

#include <sys/select.h>
#include <string.h>			// memset()
#include <unistd.h>         // read()

#include <iostream>

#include "descriptor.h"


teletype::teletype( client_type cli_type
			      , std::atomic<int> & terminate
			      , sockfd_t clisock
			      , const std::string & ip)
	: _cli_type(cli_type)
	, _terminate(terminate)
	, _clisock(clisock)
	, _cli_ip(ip)
{
	
}

teletype::~teletype()
{
	
}

void teletype::run()
{
	if (_cli_type == client_type::web)
		run_web();
	else 
		run_board();

}

void teletype::run_web()
{
	/*
	while(! _terminate) {
		std::cout << "teletype::run_web\n";
		sleep(1);
	}
	shutdown();
	*/
}

void teletype::run_board()
{
	using namespace tty::common::sys;
	
	std::cout.sync_with_stdio(true);	// Make sure std::cout is thread-safe
	std::cout << "[teletype/DEBUG] server::run_board(): client - " << _cli_ip << std::cout.flush() ;

	
	const int BUFSIZE = 1024;
	char buf[BUFSIZE];
	int nread = 0;

	while(! _terminate) {
		if (get_descriptor_status(_clisock, 0, 5000000, e_rw::read_fd, 1000)) {
			memset(buf, 0, sizeof(buf));
			nread = read(_clisock, buf, BUFSIZE);
			if (-1 == nread && errno == EINTR) break;
			
			for (int i = 0; i < nread; ++i)
				std::cout << buf[i];
			
			std::cout.flush();
		}
	}
	
}

void teletype::shutdown()
{
	close(_clisock);
}
